/*
 * File Name :  WorkModel
 */

import {
    formatAmount,
    round
} from 'math.js';
import Radio from 'backbone.radio';
import WorkItemCollection from './WorkItemCollection.js';
import ProductModel from './ProductModel.js';
import {
    bindModelValidation,
    unbindModelValidation
} from 'backbone-tools.js';
import _ from 'underscore';


const WorkModel = ProductModel.extend({
    /* props spécifique à ce modèle */
    props: [
        'title',
        'items',
        'flat_cost',
        'display_details',
    ],
    validation: {
        items: function (value) {
            if (this.items.length == 0) {
                return `Ouvrage « ${this.get('title')} » : Veuillez saisir au moins un produit`;
            }
        },
        title: {
            required: true,
            msg: "Veuillez saisir un titre"
        }
    },
    defaults() {
        let config = Radio.channel('config');
        let form_defaults = config.request('get:options', 'defaults');
        this.user_session = Radio.channel('session');
        form_defaults['tva_id'] = this.user_session.request('get', 'tva_id', form_defaults['tva_id']);
        let product_id = this.user_session.request('get', 'product_id', '');
        if (product_id !== '') {
            form_defaults['product_id'] = product_id;
        }
        form_defaults['quantity'] = 1
        form_defaults['type_'] = "price_study_work"
        form_defaults['display_details'] = true;
        return form_defaults;
    },
    initialize() {
        WorkModel.__super__.initialize.apply(this, arguments);
        this.populate();
        this.on('change:items', () => this.populate());
        this.on('saved:margin_rate', () => this.items.fetch());
    },
    populate() {
        if (this.get('id')) {
            if (!this.items) {
                this.items = new WorkItemCollection([], {
                    url: this.url() + '/' + "work_items"
                });
                this.items._parent = this;
                // this.items.stopListening(this);
                // this.items.listenTo(this, 'saved', this.items.syncAll.bind(this.items));
            }
            this.items.fetch().done(() => this.collection.trigger('fetched'));
        }
    },
    supplier_ht_label() {
        return formatAmount(round(this.get('flat_cost'), 5));
    },
    validateModel() {
        bindModelValidation(this);
        let result = this.validate() || {};
        let label = this.get('title');
        let item_validation = this.items.validate() || {};
        _.each(item_validation, function (item, index) {
            item_validation[index] = label + " " + item;
        })
        if (!_.isEmpty(item_validation)) {
            _.extend(result, {
                'subproducts': item_validation
            });
        }
        unbindModelValidation(this);
        return result;
    }
});
/*
 * On complète les 'props' du ProductModel avec celle du WorkModel
 */

WorkModel.prototype.props = WorkModel.prototype.props.concat(ProductModel.prototype.props);
Object.assign(WorkModel.prototype.validation, ProductModel.prototype.validation);
delete WorkModel.prototype.validation.description;
export default WorkModel;